#include <stdio.h>
#include <stdlib.h>
#include "Seqlist.h"
#include <string.h>


Seqtable_t* createSeqTable(int n){
    Seqtable_t* table = malloc(sizeof(Seqtable_t));
    if(table == NULL){
        printf("Table malloc failed!\n");
        return NULL;
    }

    table->data = malloc(sizeof(Element_t));
    table->pos = 0;
    table->capacity = n;

    return table;
}

void releaseSeqTable(Seqtable_t* table){
    if(table){
        if(table->data){
            free(table->data);
        }
        free(table);
    }
}

static int enlargerTable(Seqtable_t* table){
     Element_t* tmp = malloc(sizeof(Element_t)*(table->capacity*2));
    if(tmp == NULL){
        printf("malloc tamp failed!\n");
        return -1;
    }
    
    memcpy(tmp,table->data,sizeof(Element_t) * table->pos);
    table->capacity *= 2 ;
    free(table->data);
    table->data = tmp;
    return 0;
}

int insertSeqTable(Seqtable_t* table,Element_t val){// 尾插法
    if(table == NULL || table->data == NULL){
        printf("table is Null!");
        return -1;
    }

    if(table->pos == table->capacity && enlargerTable(table)){
        return -1;
    }
    table->data[table->pos] = val;
    table->pos++;
    return 0;
}  

  // 任意位置插入,慎用
int insertPosSeqTable(Seqtable_t* table,int index,Element_t val){
     if(table == NULL || table->data == NULL){
        printf("table is Null!\n");
        return -1;
    }
    if(index < 0 || index > table->pos){
        printf("index is wrong!\n");
    }
    
    if(table->pos == table->capacity && enlargerTable(table)){
        return -1;
    }

    for(int i = table->pos-1 ; i>=index ; --i){
        table->data[i+1] = table->data[i];
    }
    table->data[index] = val;
    ++table->pos;

    return 0;
}

void showSeqTable(const Seqtable_t* table){
    printf("pos / capacity :%d / %d\n",table->pos,table->capacity);
    for(int i = 0 ; i < table->pos ; i++){
        printf("%d\t",table->data[i]);
    }
    printf("\n");
}

int findSeqTable(const Seqtable_t* table,Element_t val){
    if(table == NULL){
        printf("table is Null!\n");
        return -1;
    }

    for(int i = 0; i < table->pos ; i++){
        if(table->data[i] == val){
            return i;
        }
    }
    return -1;
}

